<template>
    <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" width="60%" :height="735"
        @ok="handleSubmit">
        <a-steps :current="current" class="steps-flow">
            <a-step v-for="item in steps" :key="item.title" :title="item.title" :description="item.description" />
        </a-steps>
        <div class="steps-content scbz_box" style="width: 70%; margin: auto;">
            <div v-if="current == 0">
                <div class="lb_item">
                    <div class="lb_tit">种植计划：<span>*</span></div>
                    <div class="kuang">
                        <JDictSelectTag v-model:value="formData.growPlanId" placeholder="请选择种植计划"
                            @change="growPlanChange" dictCode="t_grow_plan,id,id" />
                    </div>
                    <div class="wxts" v-if="errmsg.growPlanId">请选择种植计划!</div>
                </div>
                <div class="lb_item">
                    <div class="lb_tit">种植作物：<span>*</span></div>
                    <div class="kuang">
                        <a-select placeholder="请选择种植作物" v-model:value="formData.growPlanProductPlotId"
                            @change="productChange">
                            <a-select-option :value="item.id" v-for="(item, index) in growPlanList" :key="index">{{
                                item.productNo_dictText }}-{{ item.plotId_dictText }}</a-select-option>
                        </a-select>
                    </div>
                    <div class="wxts" v-if="errmsg.growPlanProductPlotId">请选择种植作物!</div>
                </div>
                <div class="lb_item">
                    <div class="lb_tit">农事操作：<span>*</span></div>
                    <div class="kuang" style="position: relative;">
                        <a-select placeholder="请选择农事操作" v-model:value="formData.productionOperation"
                            @change="operationChange">
                            <a-select-option :value="item.id" v-for="(item, index) in operateList" :key="index">{{
                                item.name }}</a-select-option>
                        </a-select>
                        <a-button type="primary" style="position: absolute;height: 100%;right: 0"
                            @click="addOperation">新增操作</a-button>
                    </div>
                    <div class="wxts" v-if="errmsg.productionOperation">请选择农事操作!</div>
                </div>
                <div class="lb_item">
                    <div class="lb_tit">作业内容：</div>
                    <div class="kuang kuang1">
                        <a-textarea style="height: 100%;" v-model:value="formData.operationContent"
                            placeholder="请输入作业内容" allowClear />
                    </div>
                </div>
            </div>
            <div v-if="current == 1">
                <div class="lb_item">
                    <div class="lb_tit">投入品：</div>
                    <div class="kuang">
                        <JSelectMultiple v-model:value="formData.input" placeholder="请选择投入品"
                            dictCode="t_inputs,name,id"></JSelectMultiple>
                    </div>
                </div>
                <div class="lb_item" v-if="formData.input">
                    <div class="lb_tit">投入品用量：</div>
                    <div class="kuang sousuo">
                        <a-input v-model:value="formData.usageAndDosage" placeholder="请输入投入品用量" />
                    </div>
                </div>
                <div class="lb_item">
                    <div class="lb_tit">作业要求：</div>
                    <div class="kuang kuang1">
                        <a-textarea v-model:value="formData.operationDescription" placeholder="请输入作业要求" />
                    </div>
                </div>
                <div class="lb_item">
                    <div class="lb_tit">生产标准：</div>
                    <div class="kuang  sousuo">
                        <a-input v-model="keyword" placeholder="请输入搜索生产标准关键字" type="text" id="" class="ant-input"
                            @change="changeWord" @pressEnter="searchWord" />
                        <div class="ss_icon" @click="searchWord">
                            <img class="ss_icon_img" src="/icn_ss.png" alt="">
                        </div>
                    </div>
                    <div class="lb_item_ts">提示：点击生产标准即可展开看全部，点击 “ + ” 即可快捷添加作业要求。</div>
                    <div class="">
                        <div style="display: flex;justify-content: space-between;align-items: center;"
                            v-for="(item, index) in scbz_arr" :key="item.title">
                            <div class="kuang scbz_item" :class="{ scbz_item1: item.more, active: item.selected }"
                                @click="look(index)">
                                {{ item.title }}
                            </div>
                            <div class="lb_item_jia" @click="choice(index)"
                                :class="item.selected ? 'lb_item_jia1' : ''">
                                <svg class="lb_item_jia_img" xmlns="http://www.w3.org/2000/svg"
                                    xmlns:xlink="http://www.w3.org/1999/xlink" width="21" height="21"
                                    viewBox="0 0 21 21" fill="none">
                                    <path id="并集" fill-rule="evenodd" style="fill:#E5E7EB" opacity="1"
                                        d="M0 9L0 12L9 12L9 21L12 21L12 12L21 12L21 9L12 9L12 0L9 0L9 9L0 9Z"></path>
                                </svg>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div v-if="current == 2">
                <div class="lb_item">
                    <div class="lb_tit">作业开始时间</div>
                    <div class="kuang">
                        <a-space direction="vertical">
                            <a-date-picker v-model:value="formData.jobStartTime" valueFormat="YYYY-MM-DD HH:mm:ss"
                                :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }" @change="jobTimeChange" />
                        </a-space>
                    </div>
                    <div class="wxts" v-if="errmsg.jobStartTime">请选择作业开始时间!</div>
                </div>
                <div class="lb_item">
                    <div class="lb_tit">计划操作人<span>*</span></div>
                    <div class="jhczr">
                        <UserSelect v-model:value="formData.jobBy" :multi="true" @change="jobByChange" />
                    </div>
                    <div class="wxts" v-if="errmsg.jobBy">请选择计划操作人!</div>
                </div>
            </div>
        </div>
        <ClassificationModal @register="registerClassModal" @success="handleSuccess" />
        <template #footer>
            <div class="steps-action">
                <a-button v-if="current > 0" style="margin-right: 8px" @click="prev">上一步</a-button>
                <a-button v-if="current < steps.length - 1" type="primary" @click="next">下一步</a-button>
                <a-button v-if="current == steps.length - 1 && formData.status != -10" type="primary"
                    @click="handleSubmit">
                    提交
                </a-button>
                <a-button v-if="current == steps.length - 1 && formData.status == -10" type="primary"
                    @click="handleRelease">
                    发布
                </a-button>
            </div>
        </template>
    </BasicModal>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, unref, watch, onUnmounted } from 'vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { saveOrUpdate, changeStatus } from '../TProductionSchedule.api';
import { defHttp } from "/@/utils/http/axios";
import dayjs from 'dayjs';
import ClassificationModal from './ClassificationModal.vue';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import JSelectMultiple from "@/components/Form/src/jeecg/components/JSelectMultiple.vue";
import UserSelect from '/@/components/Form/src/jeecg/components/userSelect/index.vue'

// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);

//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

const resetFields = () => {
    Object.keys(formData).forEach(key => {
        formData[key] = ''
    })
}

const setFieldsValue = (data) => {
    Object.keys(formData).forEach(key => {
        if (data.hasOwnProperty(key)) {
            formData[key] = data[key]
        }
    })
}

const getFieldsValue = () => {
    return formData;
}

//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    if (data && data.record) {
        ['growPlanId', 'growPlanProductPlotId', 'productionOperation'].forEach(field => {
            if (!!data.record[field]) {
                data.record[field] = data.record[field].toString();
            }
        })
    }
    //重置表单
    resetFields();

    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    current.value = data?.current || 0
    if (unref(isUpdate)) {
        //表单赋值
        setFieldsValue({
            ...data.record,
            jobBy: typeof data.record.jobBy == 'object' ? data.record.jobBy.join(',') : data.record.jobBy
        });
        console.log(formData)
        await getGrowPlanList({ planId: data.record.growPlanId })
        await getOperateList()
    } else {
        // growPlanList.value = []
        // operateList.value = []
    }
});

const [registerClassModal, { openModal }] = useModal();

// 步骤条配置
const current = ref<number>(0);
const steps = [
    {
        title: '做什么？',
        description: '选择农事类型',
        content: 'First-content',
    },
    {
        title: '有无投入品？',
        description: '选投入品',
        content: 'Second-content',
    },
    {
        title: '任务分工',
        description: '指派人和时间',
        content: 'Last-content',
    },
];
const next = () => {
    validateForm(true)
};
const prev = () => {
    current.value--;
};

// 分别展示表单项
watch(current, (v) => {
    switch (v) {
        case 0:
            break;
        case 1:
            getProductionStandard('');
            break;
        case 2:
            break;
    }
})

const formData = reactive({
    id: '',
    growPlanId: '',
    growPlanProductPlotId: '',
    productionOperation: '',
    input: '',
    usageAndDosage: '',
    operationContent: '',
    operationDescription: '',
    jobStartTime: '',
    jobBy: '',
    status: 0
})

const errmsg = reactive({
    growPlanId: false,
    growPlanProductPlotId: false,
    productionOperation: false,
    jobStartTime: false,
    jobBy: false
})

const growPlanList = ref([])
const getGrowPlanList = (params: { planId: string; }) => {
    return defHttp.get({ url: '/growPlan/list', params }).then(res => {
        res.records.forEach((item, index) => {
            if (index == 0) {
                operateParams.associateId = item.product.category;
                formData.growPlanProductPlotId = item.id;
            }
        })
        growPlanList.value = res.records
    })
}
const operateList = ref([])
const operateParams = reactive({
    pid: '1689815136974086145',
    associateId: '',
    op: "op",
    pageSize: 100
})
const getOperateList = () => {
    return defHttp.get({ url: '/classification/rootList', params: operateParams }).then(res => {
        if (res.total) {
            res.records.forEach((item, index) => {
                if (index == 0) {
                    formData.productionOperation = item.id;
                }
            })
            operateList.value = res.records
        }
    })
}

const getContent = (id, no) => {
    if (!isUpdate.value || formData.operationContent == '') {
        defHttp.get({ url: '/productionSchedule/predict', params: { productionOperation: id.toString(), productNo: no } }).then(res => {
            formData.operationContent = res.predict
        }).catch(err => {
            console.warn(err)
        })
    }
}

const growPlanChange = async (value: string) => {
    growPlanList.value = [];
    operateList.value = [];
    operateParams.associateId = '';
    formData.growPlanProductPlotId = '';
    formData.productionOperation = '';
    if (!!value) {
        errmsg.growPlanId = false
        await getGrowPlanList({ planId: value })
        await getOperateList()
        growPlanList.value.filter(item => item.id == formData.growPlanProductPlotId).forEach(val => {
            getContent(formData.productionOperation, val.productNo)
        })
    }
};

const productChange = (value: string) => {
    operateList.value = [];
    operateParams.associateId = '';
    formData.productionOperation = '';
    if (value != '') {
        errmsg.growPlanProductPlotId = false
        growPlanList.value.filter(item => item.id == value).forEach(async (val) => {
            operateParams.associateId = val.product.category
            await getOperateList()
            getContent(formData.productionOperation, val.productNo)
        })
    }
};
const operationChange = (value: string) => {
    if (value != '') {
        errmsg.productionOperation = false
        growPlanList.value.filter(item => item.id == formData.growPlanProductPlotId).forEach(val => {
            getContent(value, val.productNo)
        })
    }
};
const jobTimeChange = (value: string) => {
    if (value != '') {
        errmsg.jobStartTime = false
    }
}
const jobByChange = (value: string) => {
    if (value != '') {
        errmsg.jobBy = false
    }
}

const validateFields = (data: PropertyKey[]) => {
    return new Promise<void>(function (resolve, reject) {
        let check = false;
        data.map((field: string) => {
            if (formData.hasOwnProperty(field) && formData[field] == '') {
                errmsg[field] = true
                check = true;
            }
        })
        if (check) {
            reject(false);
        } else {
            resolve();
        }
    })
}

const validateForm = async (type: boolean) => {
    switch (current.value) {
        case 0:
            validateFields(['growPlanId', 'growPlanProductPlotId', 'productionOperation']).then(_res => { type ? current.value++ : current.value--; }).catch(err => { console.log(err) });
            break;
        case 1:
            validateFields([]).then(_res => { type ? current.value++ : current.value--; }).catch(err => { console.log(err) });
            break;
        case 2:
            validateFields(['jobStartTime', 'jobBy']).then(_res => { type ? current.value++ : current.value--; }).catch(err => { console.log(err) });
            break;
    }
}

//表单提交事件
async function handleSubmit(_v: any) {
    try {
        await validateFields(['jobStartTime', 'jobBy']);
        setModalProps({ confirmLoading: true });
        //提交表单
        await saveOrUpdate(formData, isUpdate.value);
        //关闭弹窗
        closeModal();
        //刷新列表
        emit('success');
    } finally {
        setModalProps({ confirmLoading: false });
    }
}

async function handleRelease() {
    try {
        await validateFields(['jobStartTime', 'jobBy']);
        setModalProps({ confirmLoading: true });
        //提交表单
        await changeStatus({
            id: formData.id,
            status: 0
        });
        formData.status = 0
        //刷新列表
        emit('success');
    } finally {
        setModalProps({ confirmLoading: false });
    }
}

/**
 * 成功回调
 */
function handleSuccess({ isUpdate, values, expandedArr, changeParent }) {
    console.log(isUpdate, values, expandedArr, changeParent)
    getOperateList()
}

/**
   * 新增农事操作
   */
async function addOperation() {
    await validateFields(['growPlanId']);
    openModal(true, {
        isUpdate: false,
        record: {
            associateId: operateParams.associateId
        }
    });
}

const scbz_arr = ref();
const getProductionStandard = (word: string) => {
    const formData = getFieldsValue();
    if (formData.growPlanId && formData.productionOperation) {
        let params = {}
        if (word) {
            params = {
                keyWord: word
            }
        } else {
            params = {
                growPlanId: formData.growPlanId,
                productionOperation: formData.productionOperation,
                keyWord: word || ''
            }
        }
        defHttp.get({
            url: "/productionStandard/getStandByProductionOperationAndGrowPlan", params: params
        }).then(res => {
            scbz_arr.value = [];
            res.records.map((item: { content: any; }) => {
                scbz_arr.value.push({
                    title: item.content,
                    selected: false,
                    more: false,
                })
            })
        })
    }
}

const keyword = ref();
const changeWord = (e) => {
    keyword.value = e.target.value;
}
const searchWord = () => {
    getProductionStandard(keyword.value)
}

const choice = (index: string | number) => {
    scbz_arr.value[index].selected = !scbz_arr.value[index].selected
    let content = getFieldsValue().operationDescription || '';
    if (scbz_arr.value[index].selected) {
        content += scbz_arr.value[index].title
    } else {
        content = content.replace(scbz_arr.value[index].title, '');
    }
    setFieldsValue({ operationDescription: content })
}

const look = (index: string | number) => {
    scbz_arr.value[index].more = !scbz_arr.value[index].more
}

onUnmounted(() => {
})
</script>

<style lang="less">
.scbz_item {
    padding: 4px 20px;
    line-height: 30px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
    color: rgba(0, 0, 0, 0.45);
    width: 90%;
    transition: all 0.5s;

}

.lb_tit {
    margin-left: 10px;
}

.scbz_item1 {
    height: auto !important;
    white-space: wrap;
    border: 1px solid #40a9ff;
    color: #40a9ff;
    box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
}

.scbz_item:hover,
.scbz_item.active {
    border: 1px solid #40a9ff;
    color: #40a9ff;
    box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
}

.lb_item {
    margin-bottom: 30px;

    &_ts {
        font-size: 10px;
        color: #FF9233;
        padding: 20px 10px 0px;
    }

    .ant-select-arrow,
    .lb_tit span {
        color: #FF4D4F;
        margin-right: 10px;
    }

    &_jia {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: #FFF;
        border: 1px solid #E5E7EB;
        // line-height: 40px;
        text-align: center;
        font-size: 1.5rem;
        color: #E5E7EB;
        transition: all 0.5s;
        cursor: pointer;
        position: relative;

        &_img {
            width: 15px;
            height: 15px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    }

    &_jia:hover {
        border: 1px solid #40a9ff;
        box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
    }

    &_jia:hover>&_jia_img path {
        fill: #40a9ff !important;
    }

    &_jia1 {
        transform: rotate(45deg);
    }
}

.jhczr {
    margin-top: 6px;
}

.lb_item .jhczr span {
    margin-right: 0px;
    color: #333;
}

.kuang {
    height: 40px;
    opacity: 1;
    border-radius: 2px;
    background: #FFFFFF;
    border: 1px solid #E5E7EB;
    margin-top: 6px;
}

.kuang>.ant-select {
    width: 100% !important;
    height: 100% !important;
}

.kuang>.ant-select>.ant-select-selector {
    width: 100% !important;
    height: 100% !important;
    border: none;
}

.kuang>.ant-select>.ant-select-selector .ant-select-selection-search-input,
.kuang>.ant-select>.ant-select-selector .ant-select-selection-overflow,
.kuang>.ant-select>.ant-select-selector .ant-select-selection-overflow-item {
    height: 100%;
}

.kuang>.ant-select>.ant-select-selector>.ant-select-selection-item,
.kuang>.ant-select>.ant-select-selector .ant-select-selection-placeholder {
    height: 100%;
    line-height: 40px;
}

.kuang>.ant-select-multiple .ant-select-selection-item {
    height: 30px;
    line-height: 30px;
}

.kuang:hover {
    border: 1px solid #40a9ff;
    color: #40a9ff;
    box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
}

.kuang .ant-space,
.kuang .ant-space-item,
.kuang .ant-picker,
.kuang .ant-input,
.kuang .ant-input-affix-wrapper {
    width: 100% !important;
    height: 100% !important;
    border: none;
}

.kuang .ant-select-selection-search {
    margin-top: 8px;
}

.kuang1 {
    height: 180px;
}

.kuang1>.ant-input {
    width: 100%;
    height: 100%;
    border: none;
}

.wxts {
    color: #ED6F6F;
    margin-left: 10px;
    font-size: 12px;
    margin-top: 10px;
}

.scbz_list {
    display: flex;
    flex-wrap: wrap;

}

#scbz_item {
    margin: 5px;
    line-height: 36px;
    padding: 0px 15px;
    background: #fff;
    color: rgba(0, 0, 0, 0.6);
    border: 1px solid #E5E7EB;
    box-sizing: border-box;
    border-radius: 4px;
    cursor: pointer;
    transition: border-color .5s;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

#scbz_item:hover {
    border: 1px solid #40a9ff !important;
    color: #40a9ff !important;
    box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
}

.scbz_item_active {
    border: 1px solid #40a9ff !important;
    color: #40a9ff !important;
}

.steps-flow {
    width: 75%;
    margin: 30px auto;
}

/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
    width: 100%
}

:deep(.ant-calendar-picker) {
    width: 100%
}

// 步骤条样式
.steps-content {
    margin-top: 16px;
    // border: 1px dashed #e9e9e9;
    border-radius: 6px;
    // background-color: #fafafa;
    min-height: 200px;
    // text-align: center;
    padding-top: 60px;
    min-height: 500px;
}

.steps-action {
    margin-top: 24px;
    text-align: right;
}

.sousuo {
    position: relative;

    .ant-input {
        height: 100%;
        border: none;
    }

    .ss_icon {
        position: absolute;
        height: 70%;
        width: 50px;
        top: 50%;
        right: 0;
        bottom: 0;
        border-left: 1px solid #eee;
        transform: translateY(-50%);
        cursor: pointer;
    }

    .ss_icon_img {
        width: 20px;
        height: 20px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
}

[data-theme='dark'] .steps-content {
    background-color: #2f2f2f;
    border: 1px dashed #404040;
}

@media (max-width: 1550px) {
    .steps-flow {
        width: 100%;
        margin: 30px auto;
    }
}

@media (max-width: 1366px) {
    .scbz_box>.ant-col-12 {
        max-width: 70%;
    }
}

html,
body {
    font-family: PingFang SC;
}
</style>